/**
 * Created by imouze on 2017-10-26.
 *
 * 登录控制器
 */

// 用户模块
const User = require('../models/User');
const Remote = require('../remote');
const urls = require('../config/urls.json');

module.exports = {
    /**
     * 登录页
     * @param ctx
     * @param next
     * @returns {Promise.<void>}
     * @constructor
     */
    'GET /login': async (ctx, next) => {
        await ctx.render('login.html');
    },
    /**
     * 请求登录
     * @param ctx
     * @param next
     * @returns {Promise.<void>}
     * @constructor
     */
    'POST /login': async (ctx, next) => {
        
        const remote = new Remote();
        const user = new User();
        let result = {};
        
        await remote.request('POST', urls.user.login, {
            account: ctx.request.body.username,
            password: ctx.request.body.password
        }, res => {
            // console.log(res);
            result = res;
        });
        // console.log(this.body);
        ctx.response.type = 'application/json';
        ctx.cookies.set('SESSIONID', result.body.sessionid);
        ctx.response.body = {
            code: result.returncode,
            message: result.message,
            body: result.body
        };
        await next();
    },
    /**
     * 请求退出
     * @param ctx
     * @param next
     * @returns {Promise.<void>}
     * @constructor
     */
    'GET /logout': async (ctx, next) => {
        
        const remote = new Remote();
        let result = {};
        
        await remote.request('POST', urls.user.logout, {
            'JSESSIONID': ctx.cookies.get('SESSIONID')
        }, res => {
            result = res;
        });
        
        ctx.response.body = result;
        ctx.cookies.set('SESSIONID', '', {key: 'SESSIONID'});
        await next();
    }
};